/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.coreGenerator.base.entitygen.method;

import com.inspur.edp.caf.generator.baseInfo.ParameterInfo;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.method.ClassMethodGenerator;
import com.inspur.edp.cef.api.message.CefException;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.cef.generator.common.MediatePropertyInfo;
import com.inspur.edp.cef.generator.coreGenerator.base.entitygen.EntityGeneratorContext;
import com.inspur.edp.cef.generator.coreGenerator.base.entitygen.property.SimpleUdtDataValuePropGenerator;
import com.inspur.edp.cef.generator.overall.GeneratorUtil;
import com.inspur.edp.cef.generator.overall.Utils;
import com.inspur.edp.udt.designtime.api.entity.SimpleDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CreateValueGenerator extends ClassMethodGenerator {

  private static final String MethodName = "innerCreateValue";
  private static final String param1 = "propName";
  private final List<MediatePropertyInfo> propertyInfos;
  private EntityGeneratorContext parentContext;
  private final String nodeCode;

  public CreateValueGenerator(EntityGeneratorContext parentContext,
      List<MediatePropertyInfo> propertyInfos, String NodeCode) {
    this.parentContext = parentContext;
    nodeCode = NodeCode;
    this.propertyInfos = propertyInfos.stream().filter(
        item -> item.getElement() != null
            && item.getElement().getObjectType() == GspElementObjectType.Association)
        .collect(Collectors.toList());
  }

  @Override
  protected String getMethodName() {
    return MethodName;
  }

  @Override
  protected TypeInfo getReturnType() {
    return new TypeInfo(Object.class.getTypeName());
  }

  @Override
  protected boolean getIsOverride() {
    return true;
  }

  @Override
  protected ArrayList<ModifierKeyword> getAccessModifiers() {
    ArrayList<ModifierKeyword> list = new ArrayList<>();
    list.add(ModifierKeyword.PROTECTED_KEYWORD);
    return list;
  }

  @Override
  protected ArrayList<ParameterInfo> getParameterCollection() {
    ArrayList<ParameterInfo> list = new ArrayList<>();
    ParameterInfo parameterInfo = new ParameterInfo();
    parameterInfo.setParamType(new TypeInfo(String.class.getTypeName()));
    parameterInfo.setParamName(param1);
    list.add(parameterInfo);

    return list;
  }

  @Override
  protected Block buildMethodBody() {
    Block block = ast.newBlock();
    buildNewObj(block);
    if (!propertyInfos.isEmpty()) {
      SwitchStatement switchStatement = ast.newSwitchStatement();
      setSwitchExpresssion(switchStatement);
      setSwitchCases(switchStatement);
      setSwitchDefaultCase(switchStatement);
      block.statements().add(switchStatement);
    }
    buildReturnStatement(block);
    return block;
  }

  private void buildNewObj(Block block) {
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName("obj"));
    variableDeclarationFragment.setInitializer(ast.newNullLiteral());
    VariableDeclarationStatement variableDeclarationStatement = ast
        .newVariableDeclarationStatement(variableDeclarationFragment);
    variableDeclarationStatement.setType(ast.newSimpleType(ast.newSimpleName("Object")));
    block.statements().add(variableDeclarationStatement);
  }

  private void setSwitchExpresssion(SwitchStatement switchStatement) {
    switchStatement.setExpression(ast.newSimpleName(param1));
  }

  private void setSwitchCases(SwitchStatement switchStatement) {
    for (MediatePropertyInfo pi : propertyInfos) {
      buildPropertyCaseStatement(pi, switchStatement);
    }
  }

  private void buildPropertyCaseStatement(MediatePropertyInfo pi,
      SwitchStatement switchStatement) {
    SwitchCase switchCase1 = ast.newSwitchCase();
    StringLiteral stringLiteral = ast.newStringLiteral();
    stringLiteral.setLiteralValue(pi.getPropertyName());
    switchCase1.setExpression(stringLiteral);
    switchStatement.statements().add(switchCase1);

    setSwitchCaseBody(switchStatement, pi);

    switchStatement.statements().add(ast.newBreakStatement());
  }

  private void setSwitchCaseBody(SwitchStatement switchStatement, MediatePropertyInfo pi) {
    UnifiedDataTypeDef udt = Utils
        .getUdt(pi.getElement(), parentContext.getProjContext().getCefGenContext());
    TypeInfo ti = pi.getPropertyType();
    if (udt instanceof SimpleDataTypeDef) {
      ti = SimpleUdtDataValuePropGenerator
          .getSimpleUdtDataGenericType((SimpleDataTypeDef) udt);
    }
    addImport(pi.getPropertyType());

    Assignment assignment = ast.newAssignment();
    assignment.setLeftHandSide(ast.newSimpleName("obj"));
    assignment.setOperator(Assignment.Operator.ASSIGN);
    ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation();

    classInstanceCreation
        .setType(ti.getType(ast, parentContext.getProjContext()));
    assignment.setRightHandSide(classInstanceCreation);
    ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
    switchStatement.statements().add(expressionStatement);
  }

  private void setSwitchDefaultCase(SwitchStatement switchStatement) {
    SwitchCase defaultCase = ast.newSwitchCase();
    defaultCase.setExpression(null);
    switchStatement.statements().add(defaultCase);
    addImport(CefException.class.getTypeName());
    ThrowStatement throwStatement = GeneratorUtil.getThrowStatement(ast,"属性名不存在：",param1,true);;
//    ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation();

//    classInstanceCreation.setType(new TypeInfo(RuntimeException.class).getType(ast));
//
//    InfixExpression infixExpression = ast.newInfixExpression();
//    infixExpression.setOperator(InfixExpression.Operator.PLUS);
//    StringLiteral stringLiteral = ast.newStringLiteral();
//    stringLiteral.setLiteralValue("属性名不存在：");
//    infixExpression.setLeftOperand(stringLiteral);
//    infixExpression.setRightOperand(ast.newSimpleName(param1));
//    classInstanceCreation.arguments().add(infixExpression);
//
//    throwStatement.setExpression(classInstanceCreation);
    switchStatement.statements().add(throwStatement);
  }

  private void buildReturnStatement(Block block) {
    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ast.newSimpleName("obj"));
    block.statements().add(returnStatement);
  }

}
